// 提供公共的方法
let commonJs = {};
import {Toast} from 'mint-ui';

/**
 * 对toast的封装
 * @param message  消息
 * @param icon     图标
 * @param callback 回调函数
 * @param duration 显示时间
 * @param position 显示位置
 */
commonJs.openToast = function (message, icon, callback, duration, position) {
  if (message == null || message == '') {
    return;
  }
  if (icon.indexOf('success') > -1) {
    icon = 'mint-toast-icon mintui mintui-success';
  } else if (icon.indexOf('error') > -1) {
    icon = 'mint-toast-icon mintui mintui-field-error';
  } else if (icon.indexOf('warn') > -1) {
    icon = 'mint-toast-icon mintui mintui-field-warning';
  } else if (icon.indexOf('more') > -1) {
    icon = 'mint-toast-icon mintui mintui-more';
  } else {
    icon = '';
  }
  duration = duration || 2000;
  position = position || 'top';
  callback = callback || function () {
  };
  let instance = Toast({
    message: message,
    iconClass: icon,
    duration: duration,
    position: position
  });
  if (duration != '-1') {
    setTimeout(() => {
      callback();
    }, duration);
  }
  return instance;
}

/**
 * 打开ajax请求
 * @param method   请求方法
 * @param hasLoad  是否显示加载
 * @param hasError 是否显示失败
 * @returns
 */
commonJs.openAjax = async function (method, hasLoad, hasError) {
  let instance;
  if (null == hasLoad) hasLoad = true;
  if (null == hasError) hasError = false;
  if (hasLoad) {
    instance = commonJs.openToast('数据加载中', 'more', null, 60000, 'middle');
  }
  let result = await method;
  if (hasLoad && instance) {
    instance.close();
  }
  if (result.code != 0) {
    if (hasError) {
      commonJs.openToast("数据加载失败！", "error", null);
    }
  }
  return result;
};

/**
 * 返回分页数据
 * @param pageNum  第几页
 * @param pageSize 每页显示多少条数据
 * @param listData 总的数据
 * @returns
 */
commonJs.getPageData = function (pageNum, pageSize, listData) {
  pageNum = parseInt(pageNum || 1);
  pageSize = parseInt(pageSize || 10);
  let totalList = listData;
  let totalCount = totalList.length;
  let totalPage = parseInt(totalCount / pageSize);
  if (totalCount % pageSize > 0) {
    totalPage++;
  }
  let list = totalList.filter((item, index) => {
    // 获取第一页数据
    if (pageNum == 1 && index < pageSize) {
      return true;
    }
    // 不是第一页数据
    if (pageNum > 1 && index >= pageSize * (pageNum - 1) && index < pageSize * pageNum) {
      return true;
    }
  });
  return {code: 0, data: list, pageNum, totalPage, totalCount};
}

export default commonJs;
